package com.example.bookstore;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

interface changeBook {
    void changeBookList(int id);
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener, changeBook {

    private List<Book> initBookList = new ArrayList<>();//初始加载的bookList
    private List<Items> itemsList = new ArrayList<>();//加载的左导航
    RecyclerView recyclerViewRight;//右边图书list
    private List<Book> shoppingCarBook = new ArrayList<>();//购物车list
    private List<Order> orderBook = new ArrayList<>();
    RecyclerView recyclerViewCar;//购物车
    private int[] select = {1, 0, 0};
    private User user = new User();
    private LinearLayout shopping_buy;
    private LinearLayout shopping_delete;
    RecyclerView recyclerViewMe;
    LinearLayout orderLayout;
    TextView userName;
    TextView userScore;
    TextView logout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = getIntent();
        user.setAccount(intent.getStringExtra("userAccount"));
        init();
        Content.user = user;
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
        logout = (TextView) findViewById(R.id.logout);
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder  = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("你确定要退出吗?").setTitle("请确认!");
                builder.setPositiveButton("确定", (dialog, which) -> {
                    Intent intent1 = new Intent(MainActivity.this, Login.class);
                    startActivity(intent1);
                    finish();
                });
                builder.setNegativeButton("取消", null);
                builder.show();

            }
        });
        orderLayout=(LinearLayout)findViewById(R.id.recyclerList_layout);
        RecyclerView recyclerViewLeft = (RecyclerView) findViewById(R.id.item_view);//左导航List
        recyclerViewRight = (RecyclerView) findViewById(R.id.book_view);//右边书的列表
        shopping_buy = (LinearLayout)findViewById(R.id.shopping_car_buy);
        recyclerViewMe = (RecyclerView)findViewById(R.id.me_book_list_recyclerList);
        shopping_delete = (LinearLayout)findViewById(R.id.shopping_car_delete);
        userName = (TextView)findViewById(R.id.user_name);
        userScore = (TextView)findViewById(R.id.me_score);
        userScore.setText(Integer.toString(Content.user.getUserScore()));
        shopping_buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //购物车购物确定
                String temp = getData(Content.checked);
                AlertDialog.Builder builder  = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("你确定要购买吗?").setTitle("请确认!");
                builder.setPositiveButton("确定", (dialog, which) -> {
                    getShoppingCarBuy(Content.user.getAccount(),temp,WebConnect.randomStatus());
                });
                builder.setNegativeButton("取消", null);
                builder.show();
//                if(!"".equals(temp)){
//                    builder.show();
//                }

            }
        });
        shopping_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //购物车购物确定
                String temp = getData(Content.checked);
                AlertDialog.Builder builder  = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("你确定要删除吗?").setTitle("请确认!");
                builder.setPositiveButton("确定", (dialog, which) -> {

                    getShoppingCarDelete(Content.user.getAccount(),temp);
                });
                builder.setNegativeButton("取消", null);

                builder.show();

            }
        });
        recyclerViewCar = (RecyclerView)findViewById(R.id.shopping_car_recyclerList);
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(this);
        LinearLayoutManager layoutManagerCar = new LinearLayoutManager(this);
        recyclerViewMe.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewLeft.setLayoutManager(layoutManager1);
        recyclerViewRight.setLayoutManager(layoutManager2);
        recyclerViewCar.setLayoutManager(layoutManagerCar);
        recyclerViewLeft.setAdapter(new ItemAdapter(itemsList, this));
        recyclerViewRight.setAdapter(new BooksAdapter(initBookList));
    }
    public void onClickOrder(View v){

        if(v.getId()==R.id.finished_layout){
            getOrder(Content.user.getAccount(),"已完成");
        }else if(v.getId()==R.id.unpay_layout){
            getOrder(Content.user.getAccount(),"未付款");
        }else if(v.getId()==R.id.unrecieved_layout) {
            getOrder(Content.user.getAccount(),"待收货");
        }else if(v.getId()==R.id.unsent_layout){
            getOrder(Content.user.getAccount(),"已取消");
        }
    }
    private String getData(String checked) {
        String ans="";
        char[] temp = Content.checked.toCharArray();
        for(int i = 0;i<shoppingCarBook.size();++i){
            if(temp[i]=='1'){
                ans+="∫"+shoppingCarBook.get(i).getId();
            }
        }
        if(ans.equals("")){
            return ans;
        }
        return ans.substring(1);
    }

    private void init() {//初始化测试
        itemsList.add(new Items("编程", 1));
        itemsList.add(new Items("童书", 2));
        itemsList.add(new Items("漫画", 3));
        itemsList.add(new Items("经济学", 4));
        itemsList.add(new Items("生活", 5));
        itemsList.add(new Items("数学", 6));
        itemsList.add(new Items("医学", 7));
        itemsList.add(new Items("心理学", 8));
        itemsList.add(new Items("小说", 9));
        itemsList.add(new Items("科技", 10));
        getUrl("编程");
        getUser(user.getAccount());
        getCar(user.getAccount());

    }

    public void onClickSelect(View v) {
        if (v.getId() == R.id.select_enter) {
            String s = ((EditText) findViewById(R.id.select_text)).getText().toString();

            WebConnect.sendMessage(s, this, selectResult.class);
        }else if (v.getId() == R.id.select_text){
            EditText editText = (EditText) findViewById(R.id.select_text);
            showInput(editText);
        }
    }

    @Override
    public void onClick(View v) {

        LinearLayout store = (LinearLayout) findViewById(R.id.top_age);
        LinearLayout shoppingCar = (LinearLayout) findViewById(R.id.shopping);
        LinearLayout Mine = (LinearLayout) findViewById(R.id.Mine);
        store.setVisibility(View.GONE);
        shoppingCar.setVisibility(View.GONE);
        Mine.setVisibility(View.GONE);

        TextView shoppingOnclick = (TextView) findViewById(R.id.shopping_car);
        TextView mineOnclick = (TextView) findViewById(R.id.mine);
        TextView storeOnclick = (TextView) findViewById(R.id.store);

        //初始化点击颜色
        storeOnclick.setBackgroundColor(Color.WHITE);
        shoppingOnclick.setBackgroundColor(Color.WHITE);
        mineOnclick.setBackgroundColor(Color.WHITE);

        select[0] = select[1] = select[2] = 0;
        if (v.getId() == R.id.store) {
            storeOnclick.setBackgroundColor(Color.RED);
            store.setVisibility(View.VISIBLE);
            select[0] = 1;
        } else if (v.getId() == R.id.shopping_car) {
            shoppingOnclick.setBackgroundColor(Color.RED);
            shoppingCar.setVisibility(View.VISIBLE);
            shoppingCarBook.clear();
            Content.checked = "";
            getShoppingCarDelete(user.getAccount(),"");
            select[1] = 1;
        } else if (v.getId() == R.id.mine) {
            mineOnclick.setBackgroundColor(Color.RED);
            Mine.setVisibility(View.VISIBLE);
            select[2] = 1;
            recyclerViewMe.setVisibility(View.INVISIBLE);
            orderLayout.setVisibility(View.INVISIBLE);
        }
        Log.d("view", "" + v.getId());
    }

    @Override
    protected void onStart() {
        super.onStart();
        Content.checked = "";
        getShoppingCarDelete(user.getAccount(),"");
    }

    @Override
    public void changeBookList(int id) {
        Items items = itemsList.get(id);
        initBookList.clear();
        getUrl(items.getName());
    }

    public void showInput(final EditText et) {
        et.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
    }

    private void getUrl(String category){
        new Thread(()->{
            try {
                OkHttpClient client=new OkHttpClient();
                RequestBody requestBody=new FormBody.Builder()
                        .add("category",category)
                        .build();
                Request request=new Request.Builder()
                        .url("http://www.fenchingking.top/BookStore/getBookByCategory")
                        .post(requestBody)
                        .build();
                Response response=client.newCall(request).execute();
                String responseData=response.body().string();
                change(responseData);
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
    private void change(final String str){
        runOnUiThread(() ->{
                    try {
                        JSONArray jsonArray=new JSONArray(str);
                        for(int i = 0;i<jsonArray.length();++i){
                            JSONObject jsonObject =  jsonArray.getJSONObject(i);
                            initBookList.add(getBook(jsonObject));
                        }
                        recyclerViewRight.setAdapter(new BooksAdapter(initBookList));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
        );
    }
    private void getUser(String account){
        new Thread(()->{
            try {
                OkHttpClient client=new OkHttpClient();
                RequestBody requestBody=new FormBody.Builder()
                        .add("account",account)
                        .build();
                Request request=new Request.Builder()
                        .url("http://www.fenchingking.top/BookStore/getUser")
                        .post(requestBody)
                        .build();
                Response response=client.newCall(request).execute();
                String responseData=response.body().string();
                changeUser(responseData);
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
    private void changeUser(final String str){//初始化User变量
        runOnUiThread(() ->{
                    try {
                        JSONObject jsonObject = new JSONObject(str);
                        user.setId(jsonObject.getInt("id"));
                        user.setPassword(jsonObject.getString("password"));
                        user.setUserScore(jsonObject.getInt("score"));
                        user.setName(jsonObject.getString("username"));
                        user.setUserAddress(jsonObject.getString("address"));
                        Content.user = user;
                        userName.setText(jsonObject.getString("username"));
                        //userScore.setText(jsonObject.getInt("score"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }


        );
    }
    private void getCar(String account){
        new Thread(()->{
            try {
                OkHttpClient client=new OkHttpClient();
                RequestBody requestBody=new FormBody.Builder()
                        .add("account",account)
                        .build();
                Request request=new Request.Builder()
                        .url("http://www.fenchingking.top/BookStore/getShoppingCar")
                        .post(requestBody)
                        .build();
                Response response=client.newCall(request).execute();
                String responseData=response.body().string();
                changeCar(responseData);
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
    private void changeCar(final String str){
        runOnUiThread(() ->{
                    try {
                        shoppingCarBook.clear();
                        JSONArray jsonArray=new JSONArray(str);
                        for(int i = 0;i<jsonArray.length();++i){
                            JSONObject jsonObject =  jsonArray.getJSONObject(i);
                            shoppingCarBook.add(getBook(jsonObject));
                        }
                        Content.checked="";
                        for(int i = 0;i<shoppingCarBook.size();++i){
                            Content.checked+="0";
                        }
                        recyclerViewCar.setAdapter(new ShoppingCarAdapter(shoppingCarBook));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }


        );
    }
    private void getShoppingCarBuy(String account,String bookBuyList,String status){
        new Thread(()->{
            try {
                OkHttpClient client=new OkHttpClient();
                RequestBody requestBody=new FormBody.Builder()
                        .add("userAccount",account)
                        .add("bookList",bookBuyList)
                        .add("status",status)
                        .add("position","shoppingCar")
                        .build();
                Request request=new Request.Builder()
                        .url("http://www.fenchingking.top/BookStore/createOrder")
                        .post(requestBody)
                        .build();
                Response response=client.newCall(request).execute();
                String responseData=response.body().string();
                changeCar(responseData);
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
    private void getShoppingCarDelete(String account,String bookBuyList){
        new Thread(()->{
            try {
                OkHttpClient client=new OkHttpClient();
                RequestBody requestBody=new FormBody.Builder()
                        .add("account",account)
                        .add("bookList",bookBuyList)
                        .build();
                Request request=new Request.Builder()
                        .url("http://www.fenchingking.top/BookStore/deleteInShoppingCar")
                        .post(requestBody)
                        .build();
                Response response=client.newCall(request).execute();
                String responseData=response.body().string();
                changeCar(responseData);
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
    private void getOrder(String account,String status){
        new Thread(()->{
            try {
                OkHttpClient client=new OkHttpClient();
                RequestBody requestBody=new FormBody.Builder()
                        .add("userAccount",account)
                        .add("status",status)
                        .build();
                Request request=new Request.Builder()
                        .url("http://www.fenchingking.top/BookStore/getOrder")
                        .post(requestBody)
                        .build();
                Response response=client.newCall(request).execute();
                String responseData=response.body().string();
                changeOrder(responseData);
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
    private void changeOrder(final String str){
        runOnUiThread(() ->{
                    try {
                        orderBook.clear();
                        JSONArray jsonArray=new JSONArray(str);
                        for(int i = 0;i<jsonArray.length();++i){
                            JSONObject jsonObject =  jsonArray.getJSONObject(i);
                            orderBook.add(getOrderBy(jsonObject));
                        }

                        recyclerViewMe.setAdapter(new OrderAdapter(orderBook));
                        recyclerViewMe.setVisibility(View.VISIBLE);
                        orderLayout.setVisibility(View.VISIBLE);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }


        );
    }

    private Order getOrderBy(JSONObject jsonObject) throws JSONException {
        Order order = new Order();
        order.setId(jsonObject.getInt("id"));
        order.setPrice(jsonObject.getDouble("price"));
        order.setBooks(jsonObject.getString("bookList"));
        Content.bookList=order.getBooks();
        order.setSize(order.getBooks().split("∫").length);
        return order;
    }

    private Book getBook(JSONObject jsonObject) throws JSONException {
        Book book = new Book();
        book.setBookName(jsonObject.get("bookName").toString());
        book.setBookPrice(jsonObject.getString("bookPrice"));
        book.setBookRest(jsonObject.getInt("bookRest"));
        book.setBookTitle(jsonObject.getString("bookTitle"));
        book.setBookImage(jsonObject.get("bookImage").toString());
        book.setBookDescribe(jsonObject.getString("bookDescribe"));
        book.setPressDate(jsonObject.getString("pressDate"));
        book.setBookPress(jsonObject.getString("bookPress"));
        book.setBookAuthor(jsonObject.getString("bookAuthor"));
        book.setBookCategory(jsonObject.getString("bookCategory"));
        book.setId(jsonObject.getInt("bookId"));
        return book;
    }
}